from collections import defaultdict

from instance.app_instance import app
import sqlalchemy
from models.user_permission_model import UserPermissionModel

class UserModel(app.db.Model, app.db.Mixin):
    __tablename__ = 'tab_user'

    username = sqlalchemy.Column(sqlalchemy.String(50), unique=True)
    nickname = sqlalchemy.Column(sqlalchemy.String(50))
    passwd = sqlalchemy.Column(sqlalchemy.String(100))

    is_authenticated = True
    is_active = True
    is_anonymous = False

    permission = None

    def get_id(self):
        return str(self.id)

    def pre_fetch_permission(self):
        if self.permission is None:
            self.permission = UserPermissionModel.query.filter_by(user_id=get_id()).first()
            if len(self.permission.roles) > 0:
                self.permission.role_dict = set(self.permission.roles.split(','))
            else:
                self.permission.role_dict = set()
            if len(self.permission.permissions) > 0:
                self.permission.perm_dict = defaultdict(json.loads(self.permission.permissions))
            else:
                self.permission.perm_dict = defaultdict()

    def get_roles(self):
        self.pre_fetch_permission()
        if self.permission and self.permission.role_set:
            return self.permission.role_set
        return None

    def add_roles(self, roles):
        self.pre_fetch_permission()
        if self.permission and self.permission.role_set:
            self.permission.role_set |= roles
            self.permission.roles = ','.join(self.permission.role_set)
            app.db.session.commit()


    def get_projects(self):
        self.pre_fetch_permission()
        if self.permission and self.permission.perm_dict:
            if 'projects' in self.permission.perm_dict:
                return self.permission.perm_dict['projects']
        return None

    def add_project_permission(self, project_num, method):
        self.pre_fetch_permission()
        if self.permission and self.permission.perm_dict:
            methods = self.permission.perm_dict['projects'][project_num]
            methods = list(set(methods) | method)
            self.permission.perm_dict['projects'][project_num] = methods
            self.permission.permissions = json.dumps(self.permission.perm_dict)
            app.db.session.update(self.permission)
            app.db.session.commit()

